//
//  URLStream.m
//  Pennyworth Punch Clock
//
//  Created by Chris Karr on 7/16/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "URLStream.h"
#import "AppDelegate.h"

#define LOG_ACTIVE_URL @"Log_Active_URL"

@implementation URLStream

@synthesize timer;
@synthesize lastSafariUrl;
@synthesize lastFirefoxUrl;
@synthesize lastCaminoUrl;

- (void) awakeFromNib
{
	self.lastFirefoxUrl = nil;
	self.lastSafariUrl = nil;
	self.lastCaminoUrl = nil;
	
	self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update:) userInfo:nil repeats:YES];
}

- (void) update:(NSTimer *) theTimer
{
	if (![[NSUserDefaults standardUserDefaults] boolForKey:LOG_ACTIVE_URL])
		return;

	BOOL safariOpen = NO;
	BOOL firefoxOpen = NO;
	BOOL caminoOpen = NO;
	
	NSWorkspace * workspace = [NSWorkspace sharedWorkspace];
	
	NSDictionary * active = [workspace activeApplication];
	
	if ([[active valueForKey:@"NSApplicationName"] isEqual:@"Safari"])
		safariOpen = YES;
	else if ([[active valueForKey:@"NSApplicationName"] isEqual:@"Firefox"])
		firefoxOpen = YES;
	else if ([[active valueForKey:@"NSApplicationName"] isEqual:@"Camino"])
		caminoOpen = YES;
	
	NSArray * apps = [workspace launchedApplications];
	
	int i = 0;
	for (i = 0; i < [apps count]; i++)
	{
		if ([[[apps objectAtIndex:i] valueForKey:@"NSApplicationName"] isEqual:@"Safari"])
			safariOpen = YES;
		else if ([[[apps objectAtIndex:i] valueForKey:@"NSApplicationName"] isEqual:@"Firefox"])
			firefoxOpen = YES;
		else if ([[[apps objectAtIndex:i] valueForKey:@"NSApplicationName"] isEqual:@"Camino"])
			caminoOpen = YES;
	}
	
	if (safariOpen)
	{
		NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\"\n\
								  if (exists document 1) then\n\
								  URL of document 1\n\
								  end if\n\
								  end tell"];
		
		NSAppleEventDescriptor * desc = [script executeAndReturnError:nil];
		
		if (desc != nil && [desc stringValue] != nil)
		{
			NSURL * url = [NSURL URLWithString:[desc stringValue]];
			
			NSString * host = [url host];
			
			if ([url isFileURL])
				host = NSLocalizedString (@"localhost", nil);
				
			if (self.lastSafariUrl == nil || ![self.lastSafariUrl isEqualToString:host])
			{
				NSMutableDictionary * note = [NSMutableDictionary dictionary];
				[note setValue:NSLocalizedString (@"Safari Site", nil) forKey:KEY];

				if (host != nil)
					[note setValue:host forKey:PREDICTION];
				
				[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
				
				self.lastSafariUrl = host;
			}
		}
		else if (self.lastSafariUrl != nil)
		{
			NSMutableDictionary * note = [NSMutableDictionary dictionary];
			[note setValue:NSLocalizedString (@"Safari Site", nil) forKey:KEY];
			[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
			
			self.lastSafariUrl = nil;
		}
		
		[script release];
	}
	else if (self.lastSafariUrl != nil)
	{
		NSMutableDictionary * note = [NSMutableDictionary dictionary];
		[note setValue:NSLocalizedString (@"Safari Site", nil) forKey:KEY];
		[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];

		self.lastSafariUrl = nil;
	}
	
	if (firefoxOpen)
	{
		NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"Firefox\"\n\
								  set myFirefox to properties of front window as list\n\
								  get item 3 of myFirefox\n\
								  end tell"];
		
		NSAppleEventDescriptor * desc = [script executeAndReturnError:nil];
		
		if (desc != nil && [desc stringValue] != nil)
		{
			NSURL * url = [NSURL URLWithString:[desc stringValue]];
			
			NSString * host = [url host];
			
			if ([url isFileURL])
				host = NSLocalizedString (@"localhost", nil);
				
			if (self.lastFirefoxUrl == nil || ![self.lastFirefoxUrl isEqualToString:host])
			{
				NSMutableDictionary * note = [NSMutableDictionary dictionary];
				[note setValue:NSLocalizedString (@"Firefox Site", nil) forKey:KEY];

				if (host != nil)
					[note setValue:host forKey:PREDICTION];
				
				[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
				
				self.lastFirefoxUrl = host;
			}
		}
		else if (self.lastFirefoxUrl != nil)
		{
			NSMutableDictionary * note = [NSMutableDictionary dictionary];
			[note setValue:NSLocalizedString (@"Firefox Site", nil) forKey:KEY];
			[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
			
			self.lastFirefoxUrl = nil;
		}
		
		[script release];
	}
	else if (self.lastFirefoxUrl != nil)
	{
		NSMutableDictionary * note = [NSMutableDictionary dictionary];
		[note setValue:NSLocalizedString (@"Firefox Site", nil) forKey:KEY];
		[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
		
		self.lastFirefoxUrl = nil;
	}

	if (caminoOpen)
	{
		NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"Camino\"\n\
								  URL of the current tab of front window\n\
								  end tell"];
		
		NSAppleEventDescriptor * desc = [script executeAndReturnError:nil];
		
		if (desc != nil && [desc stringValue] != nil)
		{
			NSURL * url = [NSURL URLWithString:[desc stringValue]];
			
			NSString * host = [url host];
			
			if ([url isFileURL])
				host = NSLocalizedString (@"localhost", nil);
			
			if (self.lastCaminoUrl == nil || ![self.lastCaminoUrl isEqualToString:host])
			{
				NSMutableDictionary * note = [NSMutableDictionary dictionary];
				[note setValue:NSLocalizedString (@"Camino Site", nil) forKey:KEY];
				
				if (host != nil)
					[note setValue:host forKey:PREDICTION];
				
				[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
				
				self.lastCaminoUrl = host;
			}
		}
		else if (self.lastCaminoUrl != nil)
		{
			NSMutableDictionary * note = [NSMutableDictionary dictionary];
			[note setValue:NSLocalizedString (@"Camino Site", nil) forKey:KEY];
			[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
			
			self.lastCaminoUrl = nil;
		}
		
		[script release];
	}
	else if (self.lastCaminoUrl != nil)
	{
		NSMutableDictionary * note = [NSMutableDictionary dictionary];
		[note setValue:NSLocalizedString (@"Camino Site", nil) forKey:KEY];
		[[NSNotificationCenter defaultCenter] postNotificationName:PREDICTION_FETCHED object:self userInfo:note];
		
		self.lastCaminoUrl = nil;
	}
}

@end
